// API Key验证工具
import { baiduInstance } from '../api/instance';

export interface ApiKeyValidationResult {
    isValid: boolean;
    error?: string;
    details?: any;
}

export class ApiKeyValidator {
    // 验证API Key格式
    static validateApiKeyFormat(apiKey: string): ApiKeyValidationResult {
        if (!apiKey) {
            return {
                isValid: false,
                error: 'API Key不能为空'
            };
        }

        if (apiKey.length < 20) {
            return {
                isValid: false,
                error: 'API Key长度不足，请检查是否正确'
            };
        }

        if (apiKey.includes(' ')) {
            return {
                isValid: false,
                error: 'API Key包含空格，请检查是否正确'
            };
        }

        return {
            isValid: true,
            details: {
                length: apiKey.length,
                hasSpaces: apiKey.includes(' '),
                firstChars: apiKey.substring(0, 4),
                lastChars: apiKey.substring(apiKey.length - 4)
            }
        };
    }

    // 验证Secret Key格式
    static validateSecretKeyFormat(secretKey: string): ApiKeyValidationResult {
        if (!secretKey) {
            return {
                isValid: false,
                error: 'Secret Key不能为空'
            };
        }

        if (secretKey.length < 20) {
            return {
                isValid: false,
                error: 'Secret Key长度不足，请检查是否正确'
            };
        }

        if (secretKey.includes(' ')) {
            return {
                isValid: false,
                error: 'Secret Key包含空格，请检查是否正确'
            };
        }

        return {
            isValid: true,
            details: {
                length: secretKey.length,
                hasSpaces: secretKey.includes(' '),
                firstChars: secretKey.substring(0, 4),
                lastChars: secretKey.substring(secretKey.length - 4)
            }
        };
    }

    // 测试API Key有效性
    static async testApiKey(apiKey: string, secretKey: string): Promise<ApiKeyValidationResult> {
        try {
            console.log('=== 开始测试API Key ===');
            console.log('API Key:', apiKey);
            console.log('Secret Key:', secretKey.substring(0, 8) + '...');

            // 生成测试用的cuid
            const testCuid = `test_client_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
            console.log('测试cuid:', testCuid);

            // 使用baiduInstance通过代理测试，避免CORS问题
            console.log('通过vite代理发送请求...');

            const response = await baiduInstance.get('/oauth/2.0/token', {
                params: {
                    grant_type: 'client_credentials',
                    client_id: apiKey,
                    client_secret: secretKey
                }
            });

            console.log('响应状态:', response.status);
            console.log('响应头:', response.headers);

            const data = response.data;
            console.log('响应数据:', data);

            if (data.access_token) {
                return {
                    isValid: true,
                    details: {
                        access_token: data.access_token.substring(0, 20) + '...',
                        expires_in: data.expires_in,
                        token_type: data.token_type,
                        test_cuid: testCuid
                    }
                };
            } else {
                return {
                    isValid: false,
                    error: data.error_description || data.error || '未知错误',
                    details: data
                };
            }
        } catch (error: any) {
            console.error('API Key测试失败:', error);

            // 提供更详细的错误信息
            let errorMessage = '网络请求失败';
            if (error.response) {
                // 服务器响应了错误状态码
                errorMessage = `HTTP ${error.response.status}: ${error.response.statusText}`;
                console.error('服务器错误响应:', error.response.data);
            } else if (error.request) {
                // 请求已发送但没有收到响应
                errorMessage = '网络连接失败，请检查网络或代理配置';
            } else {
                // 其他错误
                errorMessage = error.message || '未知错误';
            }

            return {
                isValid: false,
                error: errorMessage,
                details: {
                    error: error.message,
                    status: error.response?.status,
                    data: error.response?.data
                }
            };
        }
    }

    // 完整的API Key验证
    static async validateApiKeys(apiKey: string, secretKey: string): Promise<ApiKeyValidationResult> {
        console.log('=== 开始完整API Key验证 ===');

        // 1. 格式验证
        const apiKeyFormat = this.validateApiKeyFormat(apiKey);
        if (!apiKeyFormat.isValid) {
            console.error('API Key格式错误:', apiKeyFormat.error);
            return apiKeyFormat;
        }

        const secretKeyFormat = this.validateSecretKeyFormat(secretKey);
        if (!secretKeyFormat.isValid) {
            console.error('Secret Key格式错误:', secretKeyFormat.error);
            return secretKeyFormat;
        }

        console.log('✅ 格式验证通过');
        console.log('API Key格式:', apiKeyFormat.details);
        console.log('Secret Key格式:', secretKeyFormat.details);

        // 2. 有效性测试
        const testResult = await this.testApiKey(apiKey, secretKey);
        return testResult;
    }
}

export default ApiKeyValidator;


